//
//  WCNPatientAddVC.m
//  WCN
//
//  Created by 杨鑫 on 15/7/2.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNPatientAddVC.h"
#import "WCNMulTextEditVC.h"
#import "WCNSelectNurseVC.h"
//
#import "WCNMulTextTCell.h"
#import "WCNSwitchSexTCell.h"
#import "WCNPatientStatusTCell.h"
#import "WCPickerView.h"
#import "WCInfoEditView.h"
#import "WCButton.h"
#import "WCDrawBorderView.h"
#import "WCNCareRecordDetailFooterView.h"
//
#import "UINavigationItem+Offset.h"
#import "UILabel+Utilities.h"
#import "NSString+Utilities.h"
#import "NSObject+Utilities.h"
//
#import "WCDefaultManager.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "WCImageManager.h"
#import "WCNConstantsCDStore.h"
#import "WCCoreDataStore.h"
#import "AccountEntity.h"
#import "Nurse.h"
//
#import "Macros.h"
#import "Constants.h"
#import "WCNHospitalListVC.h"
#import "WCImageView +setImage.h"
#import "WCNNurseModel.h"
#import "WSJCareNursingPeopleView.h"
#import "WCNMyPatientModel.h"
#import "WCDatePickerView.h"
#import "NSDate+Utilities.h"
#import "WSJPickAndCustomSegment.h"
#import "UMMobClick/MobClick.h"

static NSString *cell1 = @"WCNMulTextTCell";
static NSString *cell2 = @"WCNSwitchSexTCell";
static NSString *cell3 = @"WCNPatientStatusTCell";
static NSInteger numberOfSections = 3;
@interface WCNPatientAddVC ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) WSJCareNursingPeopleView *nurseScrollView;

//@property (weak, nonatomic) UIView *mainNurseView;
@property (strong, nonatomic) NSMutableArray *assistNurseImageViews;
@property (weak, nonatomic) UIButton *addAssistNursesButton;

@property (strong, nonatomic) WCNMulTextTCell *dynamicHeightCell;

@property (strong, nonatomic) id patientVO;
@property (strong, nonatomic) NSMutableDictionary *patient;
@property (strong, nonatomic) WCNNurseModel *mainNurse;
@property (strong, nonatomic) NSMutableArray *assistNurses;
@property (strong, nonatomic) NSArray *offerWards;

@property (strong, nonatomic) NSString *saveUrl;
@property (nonatomic) BOOL canSwitchMainNurse;

@property (nonatomic, strong) WCButton *rightBtn;

@end

@implementation WCNPatientAddVC

- (instancetype)init
{
    return [self initWithOrder:nil];
}
//增加患者进入
- (instancetype)initWithOrder:(NSString *)orderId
{
    self = [super init];
    if (self) {
        self.title = @"新增伤口患者";
        Account *accout = [[WCDefaultManager shareMg] account];
        _patient = [NSMutableDictionary dictionary];
        _patient[@"createBy"] = accout.stringId;
        if (orderId) {
            _patient[@"orderId"] = orderId;
        }
        //默认值
        _patient[@"sex"] = @"MALE";
        _patient[@"nursingType"] = @"OUT_PATIENT";
        _patient[@"nursingStatus"] = @"NURSING";
        self.patient[@"nursingLevel"] = @"一级";
        self.patient[@"isDiabetes"] = @0;
        self.mainNurse = [WCNNurseModel new];
        self.mainNurse.avatarFileId = accout.avatarFileId;
        self.mainNurse.stringId = accout.stringId;
        self.mainNurse.requestStatus = 1;
        self.mainNurse.name = accout.name;
        [self.assistNurses addObject:self.mainNurse];
        _saveUrl = @"nursing/record/add";
    }
    return self;
}

- (NSMutableArray *)assistNurses{
    if (!_assistNurses) {
        _assistNurses = [NSMutableArray array];
    }
    return _assistNurses;
}
//修改患者 进入
- (instancetype)initWithPatient:(id)patient
{
    self = [super init];
    if (self) {
        self.title = @"修改伤口患者信息";
        
        _patientVO = patient;
        
        NSDictionary *objectData = [NSObject getObjectData:patient];
        _patient = [NSMutableDictionary dictionaryWithDictionary:objectData];
        [_patient setValue:_patient[@"stringId"] forKey:@"id"];
        [_patient removeObjectForKey:@"stringId"];
        [_patient removeObjectForKey:@"mainNurse"];
        [_patient removeObjectForKey:@"woundDesc"];
        
        Account *account = [[WCDefaultManager shareMg] account];
        _patient[@"updateBy"] = account.stringId;
        
        Nurse *nurse = [patient valueForKey:@"mainNurse"];
        //设置主护理师
        if (!_mainNurse) {
            _mainNurse  =[WCNNurseModel new];
        }
        self.mainNurse.stringId =nurse.stringId;
        self.mainNurse.isPrimary = 1;
        self.mainNurse.name = nurse.name;
        self.mainNurse.avatarFileId = nurse.avatarFileId;
        self.mainNurse.requestStatus = [nurse.requestStatus integerValue];
        [self.assistNurses addObject:self.mainNurse];
        //设置共同护理师
        NSArray *array = [patient valueForKey:@"nurseMembers"];
        for (Nurse *nurse in array) {
            WCNNurseModel *model =[WCNNurseModel new];
            model.stringId =nurse.stringId;
            model.isPrimary =0;
            model.name = nurse.name;
            model.avatarFileId = nurse.avatarFileId;
            model.requestStatus = [nurse.requestStatus integerValue];
            [self.assistNurses addObject:model];
        }
        
        
        _saveUrl = @"nursing/record/update";
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];
    self.rightBtn =rightBtn;
    self.canSwitchMainNurse = NO;
    //新增可以切换主护理师
    if (!self.patient[@"id"]) {
        self.canSwitchMainNurse = YES;
    } else {
        Account *account = [[WCDefaultManager shareMg] account];
        //编辑时只有主护理师才可以切换主护理师
        if ([self.mainNurse.stringId isEqual:account.stringId]) {
            self.canSwitchMainNurse = YES;
        }
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:cell1 bundle:nil] forCellReuseIdentifier:cell1];
    [self.tableView registerNib:[UINib nibWithNibName:cell2 bundle:nil] forCellReuseIdentifier:cell2];
    [self.tableView registerNib:[UINib nibWithNibName:cell3 bundle:nil] forCellReuseIdentifier:cell3];
    
    UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 70+98+98+34)];
//    tableFooterView.backgroundColor = [UIColor redColor];
   
    self.tableView.tableFooterView = tableFooterView;
     [self loadFooterView:tableFooterView];
    //可变高度的cell
    self.dynamicHeightCell = [self.tableView dequeueReusableCellWithIdentifier:cell1];
    [self.dynamicHeightCell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.dynamicHeightCell.contentView
                                                                                   attribute:NSLayoutAttributeWidth
                                                                                   relatedBy:NSLayoutRelationEqual
                                                                                      toItem:nil
                                                                                   attribute:NSLayoutAttributeNotAnAttribute
                                                                                  multiplier:1
                                                                                    constant:kScreenWidth]];
    self.dynamicHeightCell.mulText.numberOfLines = 0;
}

- (void)save
{
    //设置护理人(主护理人和共同护理人)
    //设置护理人(主护理人和共同护理人)
    NSMutableArray *nurseIds = [NSMutableArray array];
    for (id nurse in self.assistNurses) {
        [nurseIds addObject:[nurse valueForKey:@"stringId"]];
    }
    NSMutableString *ids = [NSMutableString stringWithString:[nurseIds componentsJoinedByString:@","]];
    self.patient[@"nurseMembers"] = ids;
    
    //姓名
    NSString *name = self.patient[@"name"];
    if (!name || [name isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请填写姓名" withView:self.view];
        return;
    }
    /*
//    出生日期
    if (!self.patient[@"birthday"]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择出生日期" withView:self.view];
        return;
    }
     */
    
//    护士类型
    /*
    NSString *nursingType =  self.patient[@"nursingType"];
    if ([nursingType isEqualToString:@"RESIDENT_PATIENT"]) {
        NSString *hosPatientNo = self.patient[@"hosPatientNo"];
        if (!hosPatientNo || [hosPatientNo isEmpty]) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"请填写住院号" withView:self.view];
            return;
        }
        NSString *hosWardId = self.patient[@"hosWardId"];
        if (!hosWardId) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"请选择病区" withView:self.view];
            return;
        }
        NSString *hosBedNo = self.patient[@"hosBedNo"];
        if (!hosBedNo || [hosBedNo isEmpty]) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"请填写病床号" withView:self.view];
            return;
        }
    } else if ([nursingType isEqualToString:@"FAMILY_PATIENT"]){
        NSString *address = self.patient[@"address"];
        if (!address || [address isEmpty]) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"请填写家庭地址" withView:self.view];
            return;
        }
        NSString *contactType = self.patient[@"contactType"];
        if (!contactType) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"请选择联系人" withView:self.view];
            return;
        }
        NSString *contactPhone = self.patient[@"contactPhone"];
        if (!contactPhone || [contactPhone isEmpty]) {
            [[WCPopupLayerManager shareMg] showTextOnly:@"请填写联系方式" withView:self.view];
            return;
        }
    }
    */
    NSString *nursingStatus = self.patient[@"nursingStatus"];
    if (!nursingStatus) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择护理状态" withView:self.view];
        return;
    }
    NSString *nursingLevel = self.patient[@"nursingLevel"];
    if (!nursingLevel) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"请选择护理级别" withView:self.view];
        return;
    }
    NSString *diagnosis = self.patient[@"diagnosis"];
    if (diagnosis.length > 100) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"诊断最多可填一百个字符！" withView:self.view];
        return;
    }
    
//    MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.navigationController.view];
    CoreSVPLoading(@"同步中..", NO);
    weakSelf_define;
    self.rightBtn.enabled= NO;
    //上传患者数据
    [[WCNetworkAccessManager sharedMg] POST:self.saveUrl parameters:self.patient success:^(NSDictionary *result){
        CoreSVPSuccess(result[@"errMsg"]);
        //如果是修改状态
        if (self.patientVO) {
            //统计修改伤口患者
            [MobClick event:MotifyWoundPatient];
            //到服务器 更新病人详情
            NSString *patientId = [self.patientVO valueForKey:@"stringId"];
            NSString *urlStrng = [NSString stringWithFormat:@"nursing/record/detail/%@", patientId];
            //获得该病人详情信息
            [[WCNetworkAccessManager sharedMg] GET:urlStrng parameters:nil success:^(NSDictionary *result){
                //数据库本地 更新
                [[WCCoreDataStore shareStore] updateIdPatient:self.patientVO withData:result[@"data"]];
                [self.navigationController popViewControllerAnimated:YES];
            } failure:^(NSString *msg) {
                CoreSVPError(msg);
            } netError:^(id error) {
                CoreSVPError(error);
            } always:nil];
        } else {
            NSString *ii = AddWoundPatient;
            //统计新增伤口患者
            [MobClick event:ii];
//            CoreSVPSuccess(result[@"errMsg"]);
//            [[WCPopupLayerManager shareMg] showTextOnly:result[@"errMsg"] withView:self.view];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:PatientsRefreshNotification object:nil];
    } failure:^(NSString *msg){
        CoreSVPError(msg);
    } netError:^(id error){
        CoreSVPError(error);
    } always:^{
        weakSelf.rightBtn.enabled = YES;
    }];
}
- (void)dealloc{
    
}
#pragma mark - 加载底部图片编辑

- (void)loadFooterView:(UIView *)tableFooterView
{
    
    defineWeakSelf;
    WCDrawBorderView *view1 = [[WCDrawBorderView alloc] initWithFrame:CGRectMake(0, -kOnePX, kScreenWidth, 45+kOnePX)];
    view1.topBorder = YES;
    view1.borderColor = kBorderColor;
    
    view1.backgroundColor = [UIColor whiteColor];
    [tableFooterView addSubview:view1];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(14, 10, 200, 25)];
    label1.font = [UIFont systemFontOfSize:16.0];
    label1.text = @"主护理和共同护理人";
    [view1 addSubview:label1];
    
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth-11-13, 16, 13, 13)];
    imageView1.image = [UIImage imageNamed:@"Arrow_Down"];
    [view1 addSubview:imageView1];
    if (!self.nurseScrollView) {
        self.nurseScrollView  = [[WSJCareNursingPeopleView alloc] initWithFrame:CGRectMake(0, 60, kScreenWidth,  98 +34 +98)];
        
        self.nurseScrollView.dataArray =self.assistNurses;
        [tableFooterView addSubview:self.nurseScrollView];
        self.nurseScrollView.addNewBlok =^(){
            WCNHospitalListVC *hospitalVC =[WCNHospitalListVC new];
            
            hospitalVC.unableSelectArray = [NSArray arrayWithArray:weakSelf.assistNurses] ;
            
            hospitalVC.popCallBack = ^(NSArray *selectItems){
                for (WCNNurseModel *nurse in selectItems) {
                    nurse.requestStatus = 2;
                    [weakSelf.assistNurses addObject:nurse];
                    
                }
                
                weakSelf.nurseScrollView.dataArray = [NSArray arrayWithArray:weakSelf.assistNurses];
                
            };
            [weakSelf.navigationController pushViewController:hospitalVC animated:YES];
            
            
            
        };
        self.nurseScrollView.deleNurse  =^(WCNNurseModel *model){
            for (id nurse in weakSelf.assistNurses) {
                if ([[nurse valueForKey:@"stringId"] isEqualToString:model.stringId]) {
                    [weakSelf.assistNurses removeObject:nurse];
                    break;
                }
                
            }
        };
        
        
    }
    
}
#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    WCNMulTextTCell *cell = (WCNMulTextTCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:{
                WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                editView.titleLabel.text = @"编辑姓名";
                editView.textField.text = self.patient[@"name"];
                editView.save = ^(NSString *txt){
                    if (![txt isEmpty]) {
                        self.patient[@"name"] = txt;
                        cell.mulText.text = txt;
                        return YES;
                    }
                    return NO;
                };
                [editView showIn:self.navigationController.view animated:YES];
                break;
            }
            case 2:{
                WCDatePickerView *datePicker = [[WCDatePickerView alloc] init];
                datePicker.dateLabel.text = @"选择日期";
                
                datePicker.datePicker.maximumDate = [NSDate date];
                datePicker.close = ^(NSDate *date){
                    self.patient[@"birthday"] = [date stringWithFormat:@"yyyy-MM-dd"];
                    cell.mulText.text = [date stringWithFormat:@"yyyy-MM-dd"];;
                 };
                [datePicker show:self.navigationController completion:nil];

                break;
            }
            
            case 3:{
                WSJPickAndCustomSegment *pickVC = [[WSJPickAndCustomSegment alloc] init];
                pickVC.choosetitle = @"是否糖尿病";
                pickVC.type = 1;
                pickVC.dataSourceArray = @[@"是", @"否"];
                
                pickVC.callBack = ^(NSString *text, NSInteger item){

                    self.patient[@"isDiabetes"] = @(1 - item);
                    cell.mulText.text = text;

                
                };
                [self presentViewController:pickVC animated:YES completion:nil];
            }
                break;
            case 4:{
                WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                editView.titleLabel.text = @"白蛋白值";
                editView.textField.text = self.patient[@"albumin"];
                editView.save = ^(NSString *txt){
                    if (![txt isEmpty]) {
                        self.patient[@"albumin"] = txt;
                        cell.mulText.text = txt;
                        return YES;
                    }
                    return NO;
                };
                [editView showIn:self.navigationController.view animated:YES];
                break;
            }
            case 5:{
                WCPickerView *picker = [[WCPickerView alloc] init];
                picker.titleLabel.text = @"类型";
                picker.pickerDataSource = @[@"住院病人", @"家庭病人", @"门诊病人"];
                
                NSString *nursingType = self.patient[@"nursingType"];
                //设置默认选择视图中 选中行
                if ([nursingType isEqualToString:@"RESIDENT_PATIENT"]) {
                    [picker.picker selectRow:0 inComponent:0 animated:YES];
                } else if ([nursingType isEqualToString:@"FAMILY_PATIENT"]) {
                    [picker.picker selectRow:1 inComponent:0 animated:YES];
                }else if ([nursingType isEqualToString:@"OUT_PATIENT"]) {
                    [picker.picker selectRow:2 inComponent:0 animated:YES];
                }
                
                picker.close = ^(NSInteger selected){
                    if (selected == 0) {
                        self.patient[@"nursingType"] = @"RESIDENT_PATIENT";
                        cell.mulText.text = @"住院病人";
                    } else if (selected == 1) {
                        self.patient[@"nursingType"] = @"FAMILY_PATIENT";
                        cell.mulText.text = @"家庭病人";
                    }else if (selected == 2) {
                        self.patient[@"nursingType"] = @"OUT_PATIENT";
                        cell.mulText.text = @"门诊病人";
                    }

                    [tableView reloadData];
                };
                [picker show:self.navigationController completion:nil];
                break;
            }
            default:
                break;
        }
    } else if (indexPath.section == 1 && numberOfSections == 3) {
        NSString *nursingType = self.patient[@"nursingType"];
        if ([nursingType isEqualToString:@"RESIDENT_PATIENT"]) {
            switch (indexPath.row) {
                case 0:{
                    WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                    editView.titleLabel.text = @"住院号";
                    editView.textField.text = self.patient[@"hosPatientNo"];
                    editView.textField.keyboardType = UIKeyboardTypeASCIICapable;
                    editView.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
                    editView.save = ^(NSString *txt){
                        if (![txt isEmpty]) {
                            self.patient[@"hosPatientNo"] = txt;
                            cell.mulText.text = txt;
                            return YES;
                        }
                        return NO;
                    };
                    [editView showIn:self.navigationController.view animated:YES];
                    break;
                }
                case 1:{
                    //定义了 一个block
                    void(^selectWard)(void) = ^{
                        NSInteger wardId = [self.patient[@"hosWardId"] integerValue], index = 0;
                        //找到 默认要在选择视图中 选中的行index
                        for (Ward *ward in self.offerWards) {
                            if ([ward.stringId integerValue] == wardId) {
                                break;
                            }
                            index++;
                        }
                        
                        WCPickerView *picker = [[WCPickerView alloc] init];
                        picker.titleLabel.text = @"病区";
                        picker.pickerDataSource = self.offerWards;
                        [picker.picker selectRow:index inComponent:0 animated:YES];
                        picker.close = ^(NSInteger selected){
                            Ward *selectedWard = self.offerWards[selected];
                            self.patient[@"hosWardId"] = selectedWard. stringId;
                            self.patient[@"hosWardName"] = selectedWard.name;
    
                            cell.mulText.text = selectedWard.name;
                        };
                        [picker show:self.navigationController completion:nil];
                    };
                    
                    if (self.offerWards) {
                        selectWard();
                    } else {
                        //去服务里 拿到 科目
                        Account *account = [[WCDefaultManager shareMg] account];
                        NSString *url = [NSString stringWithFormat:@"hospital/ward/list/%@", account.hospitalId];
                        MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:self.view];
                        [[WCNetworkAccessManager sharedMg] GET:url parameters:nil success:^(NSDictionary *data){
                            //存到本地数据库
                            self.offerWards = [[WCNConstantsCDStore shareStore] createWards:data[@"data"] hospital:account.hospitalId];
                            selectWard();
                        } failure:nil netError:nil always:^{
                            [hud hide:YES];
                        }];
                    }
                    break;
                }
                case 2:{
                    WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                    editView.titleLabel.text = @"病床";
                    editView.textField.text = self.patient[@"hosBedNo"];
                    editView.textField.keyboardType = UIKeyboardTypeASCIICapable;
                    editView.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
                    editView.save = ^(NSString *txt){
                        if (![txt isEmpty]) {
                            self.patient[@"hosBedNo"] = txt;
                            cell.mulText.text = txt;
                            return YES;
                        }
                        return NO;
                    };
                    [editView showIn:self.navigationController.view animated:YES];
                    break;
                }
                default:
                    break;
            }
        } else if ([nursingType isEqualToString:@"FAMILY_PATIENT"]) {
            switch (indexPath.row) {
                case 0:{
                    WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
                    vc.title = @"地址";
                    vc.canEmpty = NO;
                    vc.textViewPlaceholder = @"请填写地址";
                    vc.textViewValue = self.patient[@"address"];
                    vc.textViewEmptyWarm = @"请填写地址";
                    vc.callback = ^(NSString *txt){
                        self.patient[@"address"] = txt;
                        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                    };
                    [self.navigationController pushViewController:vc animated:YES];
                    break;
                }
                case 1:{
                    NSArray *contacts = @[@"本人", @"儿子", @"女儿", @"父亲", @"母亲", @"其他"];
                    NSInteger index = 0;
                    NSString *contactType = self.patient[@"contactType"];
                    for (NSString *type in contacts) {
                        if ([contactType isEqualToString:type]) {
                            break;
                        }
                        index++;
                    }
                    
                    WCPickerView *picker = [[WCPickerView alloc] init];
                    picker.titleLabel.text = @"联系人";
                    picker.pickerDataSource = contacts;
                    [picker.picker selectRow:index inComponent:0 animated:YES];
                    picker.close = ^(NSInteger selected){
                        self.patient[@"contactType"] = contacts[selected];
                        cell.mulText.text = contacts[selected];
                    };
                    [picker show:self.navigationController completion:nil];
                    break;
                }
                case 2:{
                    WCInfoEditView *editView = [[WCInfoEditView alloc] init];
                    editView.titleLabel.text = @"联系方式";
                    editView.textField.text = self.patient[@"contactPhone"];
                    editView.limitLenth = 11;
                    editView.textField.keyboardType = UIKeyboardTypePhonePad;
                    editView.save = ^(NSString *txt){
                        if (![txt isEmpty]) {
                            self.patient[@"contactPhone"] = txt;
                            cell.mulText.text = txt;
                            return YES;
                        }
                        return NO;
                    };
                    [editView showIn:self.navigationController.view animated:YES];
                    break;
                
                }
                default:
                    break;
            }
        }
    } else if (indexPath.section == numberOfSections - 1) {
        switch (indexPath.row) {
            case 1:{
                NSArray *levels = @[@"特级", @"一级", @"二级", @"三级"];
                NSInteger index = 0;
                NSString *selectedLevel = self.patient[@"nursingLevel"];
                for (NSString *level in levels) {
                    if ([selectedLevel isEqualToString:level]) {
                        break;
                    }
                    index++;
                }
                
                WCPickerView *picker = [[WCPickerView alloc] init];
                picker.titleLabel.text = @"护理等级";
                picker.pickerDataSource = levels;
                [picker.picker selectRow:index inComponent:0 animated:YES];
                picker.close = ^(NSInteger selected){
                    self.patient[@"nursingLevel"] = levels[selected];
                    cell.mulText.text = levels[selected];
                };
                [picker show:self.navigationController completion:nil];
                break;
            }
            case 2:{
                WCNMulTextEditVC *vc = [[WCNMulTextEditVC alloc] initWithType:WCNMulTextEditSave];
                vc.title = @"诊断";
                vc.canEmpty = NO;
                vc.textViewPlaceholder = @"请填写诊断";
                vc.textViewValue = self.patient[@"diagnosis"];
                vc.textViewEmptyWarm = @"请填写诊断";
                vc.callback = ^(NSString *txt){
                    self.patient[@"diagnosis"] = txt;
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                };
                [self.navigationController pushViewController:vc animated:YES];
                break;
            }
            default:
                break;
        }
    }
}

//- (UITableViewCell *)sectionCell:()



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    if (indexPath.section == 0 && indexPath.row == 1) {
        WCNSwitchSexTCell *sexCell = [tableView dequeueReusableCellWithIdentifier:cell2 forIndexPath:indexPath];
        sexCell.selectionStyle = UITableViewCellSelectionStyleNone;
        sexCell.sexValueChange = ^(BOOL isMale){
            if (isMale) {
                self.patient[@"sex"] = @"FEMALE";
            } else {
                self.patient[@"sex"] = @"MALE";
            }
        };
        
        NSString *sexStr = self.patient[@"sex"];
        if ([sexStr isEqualToString:@"MALE"]) {
            [sexCell setSex:NO];
        } else {
            [sexCell setSex:YES];
        }
        
        cell = sexCell;
    } else if (indexPath.section == numberOfSections - 1 && indexPath.row == 0) { //状态
        //状态cell
        WCNPatientStatusTCell *statusCell = [tableView dequeueReusableCellWithIdentifier:cell3 forIndexPath:indexPath];
        statusCell.selectionStyle = UITableViewCellSelectionStyleNone;
        weakSelf_define;
        statusCell.btnClick = ^(NSString *status){
            weakSelf.patient[@"nursingStatus"] = status;
        };
        
        NSString *status = self.patient[@"nursingStatus"];
        if (status) {
            [statusCell setStatus:status];
        }
        
        cell = statusCell;
    } else {
        WCNMulTextTCell *normalCell = [tableView dequeueReusableCellWithIdentifier:cell1 forIndexPath:indexPath];
        normalCell.mulText.textAlignment = NSTextAlignmentRight;
        normalCell.mulText.numberOfLines = 1;
        
        if (indexPath.section == 0) {
            switch (indexPath.row) {
                case 0:{
                    normalCell.textTitle.text = @"姓名";
                    normalCell.mulText.text = self.patient[@"name"];
                    break;
                }
                case 2:{
                    normalCell.textTitle.text = @"出生日期";
                    if (self.patient[@"birthday"]) {
                        normalCell.mulText.text = [NSString stringWithFormat:@"%@", self.patient[@"birthday"]];
                    } else {
                        normalCell.mulText.text = @"";
                    }
                    break;
                }case 3:{
                    normalCell.textTitle.text = @"是否糖尿病";
                    if ([self.patient[@"isDiabetes"]  isEqual: @"1"]) {
                        normalCell.mulText.text = @"是";
                    }else{
                        normalCell.mulText.text = @"否";
                    }
                    break;
                }case 4:{
                    normalCell.textTitle.text = @"白蛋白值";
                    normalCell.mulText.text = self.patient[@"albumin"];
                    break;
                }
                case 5:{
                    normalCell.textTitle.text = @"类型";
                    NSString *nursingType = self.patient[@"nursingType"];
                    if ([nursingType isEqualToString:@"RESIDENT_PATIENT"]) {
                        normalCell.mulText.text = @"住院病人";
                    } else if ([nursingType isEqualToString:@"FAMILY_PATIENT"]) {
                        normalCell.mulText.text = @"家庭病人";
                    }else if ([nursingType isEqualToString:@"OUT_PATIENT"]) {
                        normalCell.mulText.text = @"门诊病人";
                    }
                    break;
                }
                default:
                    break;
            }
        } else if (indexPath.section == 1 && numberOfSections == 3) {
            NSString *nursingType = self.patient[@"nursingType"];
            if ([nursingType isEqualToString:@"RESIDENT_PATIENT"]) {
                switch (indexPath.row) {
                    case 0:{
                        normalCell.textTitle.text = @"住院号";
                        normalCell.mulText.text = self.patient[@"hosPatientNo"];
                        break;
                    }
                    case 1:{
                        normalCell.textTitle.text = @"病区";
                        normalCell.mulText.text = self.patient[@"hosWardName"];
                        break;
                    }
                    case 2:{
                        normalCell.textTitle.text = @"病床";
                        normalCell.mulText.text = self.patient[@"hosBedNo"];
                        break;
                    }
                    default:
                        break;
                }
            } else if ([nursingType isEqualToString:@"FAMILY_PATIENT"]) {
                switch (indexPath.row) {
                    case 0:{
                        normalCell.textTitle.text = @"家庭地址";
                        normalCell.mulText.text = self.patient[@"address"];
                        normalCell.mulText.numberOfLines = 0;
                        [normalCell.mulText showAttributedText:0 lineSpace:5];
                        break;
                    }
                    case 1:{
                        normalCell.textTitle.text = @"联系人";
                        normalCell.mulText.text = self.patient[@"contactType"];
                        break;
                    }
                    case 2:{
                        normalCell.textTitle.text = @"联系方式";
                        normalCell.mulText.text = self.patient[@"contactPhone"];
                        break;
                    }
                    default:
                        break;
                }
            }
        } else if (indexPath.section == numberOfSections - 1) {
            switch (indexPath.row) {
                case 1:{
                    normalCell.textTitle.text = @"护理级别";
                    normalCell.mulText.text = self.patient[@"nursingLevel"];
                    break;
                }
                case 2:{
                    normalCell.textTitle.text = @"诊断";
                    normalCell.mulText.text = self.patient[@"diagnosis"];
                    normalCell.mulText.numberOfLines = 0;
                    [normalCell.mulText showAttributedText:0 lineSpace:5];
                    break;
                }
                default:
                    break;
            }
        }
        
        cell = normalCell;
    }
    ///////////////
    [cell setSeparatorInset:UIEdgeInsetsZero];
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSString *nursingType = self.patient[@"nursingType"];
    if ([nursingType isEqualToString:@"OUT_PATIENT"]){
        numberOfSections = 2;
    }else {
    
        numberOfSections = 3;
    }
    return numberOfSections;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 6;
    } else if (section == 1 && numberOfSections == 3) {
        return 3;
    } else if (section == numberOfSections - 1) {
        return 3;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1 && indexPath.row == 0 && numberOfSections == 3) {
        if ([self.patient[@"nursingType"] isEqualToString:@"FAMILY_PATIENT"]) {
            self.dynamicHeightCell.mulText.text = self.patient[@"address"];
            [self.dynamicHeightCell.mulText showAttributedText:0 lineSpace:5];
            
            CGSize size = [self.dynamicHeightCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
            return MAX(kOnePX+size.height, 46.0);
        }
    } else if (indexPath.section == numberOfSections - 1 && indexPath.row == 0) {
        return 150;
    } else if (indexPath.section == numberOfSections - 1 && indexPath.row == 2) {
        self.dynamicHeightCell.mulText.text = self.patient[@"diagnosis"];
        [self.dynamicHeightCell.mulText showAttributedText:0 lineSpace:5];
        
        CGSize size = [self.dynamicHeightCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        return MAX(kOnePX+size.height, 46.0);
    }
    
    return 46;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    WCDrawBorderView *view = [[WCDrawBorderView alloc] init];
    view.topBorder = YES;
    view.bottomBorder = YES;
    view.borderColor = kBorderColor;
    view.backgroundColor = kAppBg;
    
    UILabel *label = [[UILabel alloc] init];
    label.translatesAutoresizingMaskIntoConstraints = NO;
    label.font = [UIFont systemFontOfSize:15.0];
    label.textColor = HexRGB(0x888888);
    switch (section) {
        case 0:
            label.text = @"患者基本信息";
            break;
        case 1:{
            NSString *nursingType = self.patient[@"nursingType"];
            if ([nursingType isEqualToString:@"RESIDENT_PATIENT"]) {
                label.text = @"住院信息";
            } else if ([nursingType isEqualToString:@"FAMILY_PATIENT"]) {
                label.text = @"家庭病床信息";
            }else if ([nursingType isEqualToString:@"OUT_PATIENT"]) {
                label.text = @"设置";
            }
            break;
        }
        case 2:
            label.text = @"设置";
            break;
        default:
            break;
    }
    [label addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeHeight
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:nil attribute:NSLayoutAttributeNotAnAttribute
                                                     multiplier:0 constant:25]];
    
    [view addSubview:label];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeLeading
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:view attribute:NSLayoutAttributeLeading
                                                    multiplier:1 constant:14]];
    [view addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeBottom
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:view attribute:NSLayoutAttributeBottom
                                                    multiplier:1 constant:0]];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 32;
}

@end
